package com.phone580.app.net;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.util.Log;

import com.phone580.app.CommonData;

public class HttpAccess {
	protected static final String tag = "phone580";
	private static final int timeoutConnection = 3000;  
	private static final int timeoutSocket = 5000; 
	
	public static final String login(Context context, String username, String password) throws ClientProtocolException, IOException {
		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(CommonData.LOGIN_URL);
		List <NameValuePair> params=new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username", username));
		params.add(new BasicNameValuePair("password", password));
		request.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
		HttpResponse response = client.execute(request);
		String data = null;
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			data = EntityUtils.toString(response.getEntity(), "UTF-8");
			Log.d(tag, "login return:" + data);
		} else {
			Log.d(tag, "request error:" + response.getStatusLine().toString());
		}
		return data;
	}
	
	/**
	 * get请求
	 * @param url
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static final String doGet(String url) throws ClientProtocolException, IOException {
		BasicHttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established.  
	    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data.  
	    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);  
		HttpClient client = new DefaultHttpClient(httpParameters); 
		url += "?tm=" + System.currentTimeMillis();
		Log.d(tag, "url:" + url);
		HttpGet request = new HttpGet(url);
		HttpResponse response = client.execute(request);
		String data = null;
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			data = EntityUtils.toString(response.getEntity(), "UTF-8");
			Log.d(tag, "get return:" + data);
			return data;
		} else {
			Log.d(tag, "request error:" + response.getStatusLine().toString());
		}
		return data;
	}
	
	public static final String doGet(String url, Map<String, String> params) throws ClientProtocolException, IOException {
		HttpClient client = new DefaultHttpClient();
		url += "?tm=" + System.currentTimeMillis();
		for (String key : params.keySet()) {
			url += "&" + key + "=" + params.get(key);
		}
		Log.d(tag, "url:" + url);
		HttpGet request = new HttpGet(url);
		HttpResponse response = client.execute(request);
		String data = null;
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			data = EntityUtils.toString(response.getEntity(), "UTF-8");
			Log.d(tag, "get return:" + data);
			return data;
		} else {
			Log.d(tag, "request error:" + response.getStatusLine().toString());
		}
		return data;
	}
	
	public static boolean doPost(String url,Map<String,String> params)	throws Exception{
		Log.d(tag, "url:" + url);
        List <NameValuePair> pairs=new ArrayList<NameValuePair>();
        if(params!=null&&!params.isEmpty()){
        	for(Map.Entry<String, String> entry : params.entrySet()){
        		pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        	}
        }
        UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairs,"UTF-8");
        HttpPost post=new HttpPost(url);
        post.setEntity(entity);
        DefaultHttpClient client=new DefaultHttpClient();
        HttpResponse response=client.execute(post);
        String data = EntityUtils.toString(response.getEntity(), "UTF-8");
		Log.d(tag, "get return:" + data);
        if(response.getStatusLine().getStatusCode()==200){
        	return true;
        }
        return false;
    }
	
	public static String doPostWithResult(String url,Map<String,String> params)	throws Exception{
		Log.d(tag, "url:" + url);
        List <NameValuePair> pairs=new ArrayList<NameValuePair>();
        if(params!=null&&!params.isEmpty()){
        	for(Map.Entry<String, String> entry : params.entrySet()){
        		pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        	}
        }
        UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairs,"UTF-8");
        HttpPost post=new HttpPost(url);
        post.setEntity(entity);
        DefaultHttpClient client=new DefaultHttpClient();
        HttpResponse response=client.execute(post);
        
        String data = null;
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			data = EntityUtils.toString(response.getEntity(), "UTF-8");
			Log.d(tag, "get return:" + data);
			return data;
		} else {
			Log.d(tag, "request error:" + response.getStatusLine().toString());
		}
		return data;
    }
	
	public static void downloadFile(String url, String savePath) throws IOException {
		URL httpurl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection)httpurl.openConnection();
		byte[] b = new byte[4096];
		FileOutputStream fos = new FileOutputStream(new File(savePath));
		int len = 0;
		InputStream in = connection.getInputStream();
		while ((len = in.read(b, 0, b.length)) != -1) {
			fos.write(b, 0, len);
		}
		fos.close();
		in.close();
		connection.disconnect();
	}
	
	public static byte[] downloadFile(String url) throws IOException {
		URL httpurl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection)httpurl.openConnection();
		byte[] b = new byte[4096];
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int len = 0;
		InputStream in = connection.getInputStream();
		while ((len = in.read(b, 0, b.length)) != -1) {
			bos.write(b, 0, len);
		}
		connection.disconnect();
		byte[] data = bos.toByteArray();
		bos.close();
		return data;
	}
}
